package com.ds.infrastructure.audit.collector.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ds.infrastructure.audit.collector.constant.CollectorConstant;
import com.ds.infrastructure.audit.collector.entity.App;
import com.ds.infrastructure.audit.collector.mapper.AppMapper;
import com.ds.infrastructure.audit.collector.service.IAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/4
 */
@Service
@Slf4j
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements IAppService {

    @Resource
    private HashOperations<String, String, App> hashOperations;

    @PostConstruct
    public void init() {
        Long size = hashOperations.size(CollectorConstant.KEY_KBATRACK_AUDIT_APP);
        if (size < 1) {
            QueryWrapper<App> wrapper = Wrappers.query();
            List<App> appList = list(wrapper.eq(CollectorConstant.COLUMN_IS_DEL, CollectorConstant.STATE_NORMAL));
            if (CollectionUtils.isNotEmpty(appList)) {
                for (App app : appList) {
                    hashOperations.put(CollectorConstant.KEY_KBATRACK_AUDIT_APP, getKey(app.getAppName(), app.getAppKey()), app);
                }
                log.info("Init App success");
            }
        }
        log.info("====App Cache Size={}", hashOperations.size(CollectorConstant.KEY_KBATRACK_AUDIT_APP));
    }

    @Override
    public String getKey(String appName, String appKey) {
        return appName + "#" + appKey;
    }

    /**
     * 通过appName,appKey查询
     *
     * @param appName
     * @param appKey
     * @return
     */
    @Override
    public App queryByCondition(String appName, String appKey) {
        QueryWrapper<App> wrapper = Wrappers.query();
        return this.getOne(wrapper.eq(CollectorConstant.COLUMN_APPNAME, appName).eq(CollectorConstant.COLUMN_APPKEY, appKey));
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void saveApp(App app) {
        app.setAppKey(IdUtil.fastSimpleUUID());
        super.save(app);
        String key = getKey(app.getAppName(), app.getAppKey());
        App application = this.getById(app.getId());
        hashOperations.put(CollectorConstant.KEY_KBATRACK_AUDIT_APP, key, application);
        log.info("Add New APP Success :: {}", key);
    }

    /**
     * 删除APP
     *
     * @param appId
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteAppById(Long appId) {
        App app = this.getById(appId);
        String key = getKey(app.getAppName(), app.getAppKey());
        boolean b = this.removeById(appId);
        if (b) {
            Long cnt = hashOperations.delete(CollectorConstant.KEY_KBATRACK_AUDIT_APP, key);
            if (cnt < 1) {
                //todo: 告警
                log.warn("Delete App Cache Fail :: {},{}", key, appId);
            } else {
                log.info("Delete APP Success :: {},{}", key, appId);
                return true;
            }
        } else {
            log.warn("Delete App Fail :: {},{}", key, appId);
        }
        return false;
    }

    /**
     * 更新APP
     *
     * @param app
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean updateApp(App app) {
        app.setAppName(null);
        app.setAppKey(null);
        boolean b = super.updateById(app);
        if (b) {
            App application = this.getById(app.getId());
            if (application != null) {
                String key = getKey(application.getAppName(), application.getAppKey());
                hashOperations.put(CollectorConstant.KEY_KBATRACK_AUDIT_APP, key, application);
                log.info("Update APP Success :: {}", key);
                return true;
            }
        } else {
            log.warn("Update App Fail :: {}", app.getId());
        }
        return false;
    }

    /**
     * 判断是否为注册APP
     *
     * @param appName
     * @param appKey
     * @return
     */
    @Override
    public boolean isRegisteredApp(String appName, String appKey) {
//        Long size = hashOperations.size(CollectorConstant.KEY_KBATRACK_AUDIT_APP);
//        if (size < 1) {
//            log.warn("App Cache Empty");
//            //TODO: 发送短信告警
//            return true;
//        }
        //查询缓存 判断是否存在
        String key = getKey(appName, appKey);
        //if (hashOperations.hasKey(CollectorConstant.KEY_KBATRACK_AUDIT_APP, key)) {
            App app = hashOperations.get(CollectorConstant.KEY_KBATRACK_AUDIT_APP, key);
            return app != null && app.getIsDel().equals(CollectorConstant.STATE_NORMAL);
        //}
        //return false;
    }

}
